<?php

namespace App\Console\Commands;

use App\Models\{
    Role,
    Permission,
};
use Illuminate\Console\Command;

class CreateRole extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'role:create 
                            {name : Name of role}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Creating role and assign them permissions';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $allPermissions = Permission::all();

        if (0 === $allPermissions->count()) {
            $this->info('Please create permissions before role creation.');

            return 1;
        }

        $validator = \Validator::make([
            'role_name' => $this->argument('name'),
        ], [
            'role_name' => [
                'required',
                'max:50',
                'string',
                'unique:roles',
            ],
        ]);

        if ($validator->fails()) {
            $this->info('Role not created. See errors below:');

            foreach ($validator->errors()->all() as $error) {
                $this->error($error);
            }

            return 1;
        }

        $role = new Role($validator->validated());

        $permissions = $this->choice(
            'Which permissions assign to this role?',
            $allPermissions->pluck('permission_name', 'permission_id')->toArray(),
            null,
            null,
            true
        );
        $selectedPermissions = $allPermissions->whereIn('permission_name', $permissions);

        \DB::transaction(static function () use ($role, $selectedPermissions) {
            $role->save();
            $role->permissions()->attach($selectedPermissions);
        });
        $this->info(\sprintf('Role %s was created with given permissions.', $role->role_name));

        return 0;
    }
}
